package com.rljk.controller.app;

import com.rljk.common.controller.BaseController;
import com.rljk.common.result.CodeMsg;
import com.rljk.common.result.Result;
import com.rljk.domain.common.PageData;
import com.rljk.redis.RedisService;
import com.rljk.service.UserManager;
import com.rljk.service.impl.AssetsService;
import com.rljk.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:   YASUO
 * Date:     2018/6/27 11:27
 * Description: 用户接口
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserInController extends BaseController{

    @Resource(name = "userService")
    private UserManager userService;

    @Autowired
    RedisService redisService;

    @Resource(name = "assetsService")
    private AssetsService assetsService;

    /**
     * 用户登陆接口    ——此接口没用
     * author:YASUO
     * date:2018/6/27
     */
    @RequestMapping(value="/login")
    public Object userLogin(HttpServletRequest request) {
        log.info("用户登陆接口");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("USERLOGIN", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("userLogin",pd)){
                    //map.put("taskList",taskList);
                    //Cookie uuid = CookieUtil.get(request, Const.SESSION_SECURITY_CODE);


                    return Result.success(map);
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * 更新用户经纬度接口
     * author:YASUO
     * date:2018/6/27
     */
    @RequestMapping(value="/updlocation")
    public Object updLocation() {
        log.info("更新用户经纬度接口");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("UPDLOCATION", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("updLocation",pd)){
                    String token = redisService.get(pd.getString("TOKEN"));
                    if(Tools.isEmpty(token)){
                        return Result.error(CodeMsg.TOKEN_ERROR);
                    }
                    pd.put("USER_ID",token);
                    userService.edit(pd);
                    return Result.success();
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * @Author zhang
     * @Description APP注册用户
     * @Date 2018/8/13 9:45
     * @Param [request]
     * @return java.lang.Object
     **/
    @RequestMapping(value="/registeruser")
    public Object appRegisterUser(HttpServletRequest request) {
        log.info("APP注册用户");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("APPREGISTERUSER", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("appRegisterUser",pd)){

                    String redisCode =redisService.get(Const.ALI_CODE+pd.getString("PHONE"));
                    String code = (String) pd.get("CODE");
                    if (StringUtils.equals(redisCode,code)){

                        PageData byPhone = userService.findByPhone(pd);
                        if (byPhone == null){
                            String userId = this.getSnowId();
                            pd.put("USER_ID",userId);
                            String password = (String) pd.get("PASSWORD");
                            String SALT = DateUtil.getdaySFM();
                            String md5Password = MD5.getPassword(password + SALT);
                            pd.put("PASSWORD",md5Password);
                            pd.put("SALT", SALT);

                            userService.save(pd);
                            //初始化资产
                            pd.put("ASSETS_ID",this.getSnowId());
                            assetsService.save(pd);

                            return Result.success(CodeMsg.REGIST_SUCCESS);
                        }else {
                            return Result.error(CodeMsg.REGIST_ERROT);
                        }
                    }else {
                        return Result.error(CodeMsg.CODE_ERROR);
                    }


                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * 设置-退出当前账号
     * author:YASUO
     * date:2018/8/13
     */
    @RequestMapping(value="/loginout")
    public Object loginOut() {
        log.info("设置-退出当前账号");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        try {
            if (Tools.checkKey("LOGINOUT", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("useridParam",pd)){
                    String token = redisService.get(pd.getString("TOKEN"));
                    if(Tools.isEmpty(token)){
                        return Result.error(CodeMsg.TOKEN_ERROR);
                    }
                    redisService.del(pd.getString("TOKEN"));
                    return Result.success();
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * @Author zhang
     * @Description  APP用户登录
     * @Date 2018/8/13 10:11
     * @Param [request]
     * @return java.lang.Object
     **/
    @RequestMapping(value="/loginuser")
    public Object APPLoginUser(HttpServletRequest request) {
        log.info("APP用户登录");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("APPLOGINRUSER", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("APPLoginUser",pd)){

                    PageData byPhone = userService.findByPhone(pd);

                    if (byPhone == null){
                        return Result.error(CodeMsg.LOGIN_ERROR);
                    }else {
                        if (StringUtils.equals((String)byPhone.get("PHONE"),(String)pd.get("PHONE"))){
                            String password = (String) pd.get("PASSWORD");
                            String SALT = (String) byPhone.get("SALT");
                            String md5Password = MD5.getPassword(password + SALT);
                            if (!md5Password.equals(byPhone.get("PASSWORD"))){
                                return Result.error(CodeMsg.LOGIN_ERROR);
                            }else {
                                String TOKEN = this.getSnowId();
                                redisService.setex(TOKEN, byPhone.getString("USER_ID"),60*60*24*30);
                                log.info("用户TOKEN:"+TOKEN);

                                map.put("TOKEN",TOKEN);
                                map.put("USERNAME",byPhone.get("USERNAME"));
                                map.put("PORTRAIT",byPhone.get("PORTRAIT"));
                                return Result.success(map);
                            }
                        }
                        return Result.error(CodeMsg.LOGIN_ERROR);
                    }

                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }

    }

    /**
     * 星我星球二维码邀请下载
     * author:YASUO
     * date:2018/8/14
     */
    @RequestMapping(value="/qqcodedown")
    public Object qqcodeDown() {
        log.info("星我星球二维码邀请下载");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map =new HashMap<>();
        try {
            if (Tools.checkKey("QQCODEDOWN", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("useridParam",pd)){
                    String token = redisService.get(pd.getString("TOKEN"));
                    PageData qRcodeAndNumber = userService.getQRcodeAndNumber(token);
                    String qrcode = "";
                    int QRCODE_NUMBER = 10;
                    if(qRcodeAndNumber==null){
                        qrcode = ToolsUtil.noRepeatCode();
                        pd.put("QRCODE",qrcode);
                        pd.put("QRCODE_NUMBER",QRCODE_NUMBER);
                        pd.put("USER_ID",token);
                        userService.edit(pd);
                    }else{
                        qrcode = qRcodeAndNumber.getString("QRCODE");
                        QRCODE_NUMBER = qRcodeAndNumber.getInterger1("QRCODE_NUMBER");
                    }
                    map.put("QRCODE",qrcode);
                    map.put("QRCODE_NUMBER",QRCODE_NUMBER);
                    map.put("QRCODE_IMG",Const.QQCODE_IMG);
                    return Result.success(map);
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }

    }


    /**
     * @Author zhang
     * @Description  密码重置接口
     * @Date 2018/8/14 13:49
     * @Param [request]
     * @return java.lang.Object
     **/
    @RequestMapping(value="/reset")
    public Object resetPW(HttpServletRequest request) {
        log.info("密码重置接口");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("RESETPW", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("resetPW",pd)){

                    String redisCode =redisService.get(Const.ALI_CODE+pd.getString("PHONE"));
                    String code = (String) pd.get("CODE");
                    if (StringUtils.equals(redisCode,code)){

                        String password = (String)pd.get("PASSWORD");
                        String confirmpassword = (String) pd.get("CONFIRMPASSWORD");

                        if (StringUtils.equals(password,confirmpassword)){

                            PageData byPhone = userService.findByPhone(pd);
                            if (byPhone == null){
                                return Result.error(CodeMsg.MOBILE_NOT_EXIST);
                            }else {
                                    String SALT = DateUtil.getdaySFM();
                                    String md5Password = MD5.getPassword(password + SALT);
                                    pd.put("PASSWORD",md5Password);
                                    pd.put("SALT", SALT);
                                    pd.put("USER_ID", byPhone.get("USER_ID"));
                                    userService.edit(pd);

                                return Result.success(CodeMsg.RESET_SUCCESS);
                            }
                        }else {
                            return Result.error(CodeMsg.RESET_ERROT);
                        }


                    }else {
                        return Result.error(CodeMsg.CODE_ERROR);
                    }

                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * h5测试上传
     * @Author zhaozhenhua
     * @date   2018年8月622日
     * @return
     */
    @RequestMapping(value="/uploadimg")
    @ResponseBody
    public Object uploadImg(MultipartHttpServletRequest mreq, HttpServletResponse resp, HttpServletRequest request, String FKEY,
                                             String CATEGORY_ID, String  APPLYFOR_NAME){
        log.info("h5测试上传");
        Map<String,Object> map = new HashMap<String,Object>();
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("FKEY", FKEY);
        log.info("pd的值："+pd.get("uploadimgs"));
        String uploadimgs ="";
        try{
//            if(Tools.checkKey("APPUPLOADS", pd.getString("FKEY"))){	//检验请求key值是否合法
                //if(AppUtil.checkParam("addApplyBusiness", pd)){	//检查参数
                //从redis中获取验证码

                uploadimgs = FTPUtils.upMultiImgs(mreq, resp, "file", "gemstone/test");
                if(Tools.notEmpty(uploadimgs)){
                    uploadimgs+=","+uploadimgs;
                }
                return Result.success(uploadimgs);

				/*}else {
					result = "03";
				}*/
            /*}else{
                return Result.error(CodeMsg.FKEY_FAIL);
            }*/
        }catch (Exception e){
            log.error(e.toString(), e);
        }
        return null;
    }


}
